package vn.demand.dragon.model
{
	import mx.collections.XMLListCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import vn.demand.dragon.CommonCommand;
	import vn.demand.dragon.model.business.LoadSuppliersDelegate;
	import vn.demand.dragon.model.business.RemoveSupplierDelegate;
	import vn.demand.dragon.model.business.SaveSupplierDelegate;
	import vn.demand.dragon.model.vo.Supplier;
	
	public class SupplierProxy extends Proxy implements IProxy, IResponder
	{
		public static const NAME:String = "SupplierProxy";
		
		public function SupplierProxy(proxyId:String = NAME)
		{
			super(proxyId);
		}
		
		public function saveSupplier(supplierVO:Object):void {
			var delegate:SaveSupplierDelegate = new SaveSupplierDelegate(this);
			delegate.saveSupplier(supplierVO);
		}

		// this is called when the delegate receives a result from the service
		public function result( rpcEvent : Object ) : void
		{
			var success:Boolean = rpcEvent.result.success == 'true'; 
			if (success) {
				var supplierVO:Supplier = rpcEvent.token.supplierVO as Supplier;
				supplierVO.sup_id = int(rpcEvent.result.sup_id);
				sendNotification(CommonCommand.SUPPLIER_ADDED, supplierVO);
			} else {
				errorStatus = rpcEvent.result.errors;
				sendNotification(CommonCommand.SUPPLIER_ADD_FAILED, errorStatus);				
			}
		}
		
		// this is called when the delegate receives a fault from the service
		public function fault( rpcEvent : Object ) : void 
		{
			errorStatus = "Something wrong when save quotation lines!";
			//sendNotification(FFIAApplicationFacade.TASK_LOG_UPDATE_FAILED, errorStatus, projectVO.project_id);
		}

		public function search(params:Object=null):void {
			var delegate:LoadSuppliersDelegate = new LoadSuppliersDelegate(
				function(rpcEvent : Object) {
					var list:XMLListCollection = new XMLListCollection(rpcEvent.result.suppliers.supplier);
					sendNotification(CommonCommand.LOAD_SUPPLIERS_SUCCESSFUL, list);
				},
				function(rpcEvent : Object) {
					sendNotification(CommonCommand.LOAD_SUPPLIERS_FAILED);
				});
			delegate.searchSupplierService(params);
		}
		
		public function remove(params:Object):void {
			var delegate:RemoveSupplierDelegate = new RemoveSupplierDelegate(
				function(rpcEvent : Object) {
					var supplierVO:Supplier = rpcEvent.token.supplierVO as Supplier;
					var success:Boolean = rpcEvent.result.success == 'true'; 
					if (success) {
						sendNotification(CommonCommand.SUPPLIER_REMOVED, supplierVO);
					} else {
						sendNotification(CommonCommand.SUPPLIER_REMOVE_FAILED, String(rpcEvent.result.errors));
					}
				},
				function(rpcEvent : Object) {
					sendNotification(CommonCommand.SUPPLIER_REMOVE_FAILED, 'Some thing wrong...');
				});
			delegate.removeSupplier(params);
		}

		[Bindable] public var errorStatus:String = null;
	}
}